package cfengMiddleware.server.service.impl;

import CfengMiddleWare.model.entity.MqOrder;
import CfengMiddleWare.model.entity.UserOrder;
import CfengMiddleWare.model.mapper.MqOrderMapper;
import CfengMiddleWare.model.mapper.UserOrderMapper;
import cfengMiddleware.server.dto.UserOderDto;
import cfengMiddleware.server.rabbitmq.entity.MessageEntity;
import cfengMiddleware.server.rabbitmq.producer.DeadProducer;
import cfengMiddleware.server.service.DeadUserOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/9/18
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DeadUserOrderServiceImpl implements DeadUserOrderService {

    //死信队列生产者，用于将消息发布到死信队列处理
    private final DeadProducer deadProducer;

    //数据库表的dao
    private final UserOrderMapper userOrderMapper;

    private final MqOrderMapper mqOrderMapper;

    @Override
    public void pushUserOrder(UserOderDto userOderDto) throws Exception {
        //用户下单
        UserOrder userOrder = new UserOrder();
        //对象复制，属性复制
        BeanUtils.copyProperties(userOderDto,userOrder);
        //设置支付状态为已保存
        userOrder.setStatus(1);
        //设置下单时间
        userOrder.setCreateTime(LocalDateTime.now());
        //插入下单记录,这里应该是同步的，必须要将记录插入数据库
        userOrderMapper.insert(userOrder);
        log.info("用户下单成功,下单信息： {}",userOrder);
        //压入死信队列，默认就是异步的, 上面Order生成了一个默认的ID
        Integer orderId = userOrder.getId();
        //将该ID压入死信队列，这里Cfeng为了复用直接修改MessageEntity
        deadProducer.sendDeadMessage(new MessageEntity(orderId));
    }

    //商品失效的处理
    @Override
    public void updateUserOrderRecord(UserOrder userOrder) {
        try {
            if(!Objects.isNull(userOrder)) {
                //更新失效用户的下单记录
                userOrder.setIsActive(0);
                //更新时间
                userOrder.setUpdateTime(LocalDateTime.now());
                //下单实体更新
                userOrderMapper.updateById(userOrder);

                //下单历史记录，mqOrder
                MqOrder mqOrder = new MqOrder();
                mqOrder.setBusinessTime(LocalDateTime.now());
                mqOrder.setOrderId(userOrder.getId());
                //信息
                mqOrder.setMemo("更新失效的当前用户下单的记录ID，orderID= " + userOrder.getId());
                mqOrderMapper.insert(mqOrder);
            }
        } catch (Exception e) {
            log.error("用户下单支付超时业务： 更新失效订单异常 {}",e.fillInStackTrace());
        }
    }
}
